package com.example.springbootrbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootrbac.entity.UserEntity;
import com.example.springbootrbac.param.UserParam;
import com.example.springbootrbac.pojo.Result;
import com.example.springbootrbac.pojo.ResultCode;
import com.example.springbootrbac.repository.UserRepository;
import com.example.springbootrbac.service.UserService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController   // = @Controller + @ResponseBody
public class UserController {  //与用户相关的操作

    @Resource(name = "userServiceImpl")
    UserService userService;

    @PostMapping("/login")   //登录功能,已经被弃用，改用Security自带的
    public Result<String> login(@Validated UserParam userParam, HttpServletRequest request) {  //DataBinder数据绑定：将数据合并绑定到对象中，对象属性名必须与前端相同
        System.out.println(userParam);
        if(userParam.getUsername().isEmpty() || userParam.getPassword().isEmpty())
            return Result.failure(ResultCode.FAILURE_USERNAME_OR_PASSWORD_EMPTY);
        String token = userService.login(request,userParam.getUsername(),userParam.getPassword());

        if (ObjectUtils.isEmpty(token)){
            return Result.failure(ResultCode.FAILURE_USERNAME_OR_PASSWORD_ERROR);
        }
        String s = "欢迎"+userParam.getUsername()+"到来♪";
        return Result.success(s,token);
    }


    @PostMapping("/register")  //注册功能
    public Result<String> registered(@Validated UserParam userParam){
        if(userParam.getUsername().isEmpty() || userParam.getPassword().isEmpty())
            return Result.failure(ResultCode.FAILURE_USERNAME_OR_PASSWORD_EMPTY);

        String token = userService.registered(userParam.getUsername(),userParam.getPassword());
        if (ObjectUtils.isEmpty(token)){
            return Result.failure(ResultCode.FAILURE_REGISTERED_ERROR);
        }
        String s = "欢迎"+userParam.getUsername()+"加入了我们♪";
        return Result.success(s,token);
    }
}
